package posts

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPostsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 香评详情 ##25.04.01## 历史遗留文件，暂不处理
func NewGetPostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostsLogic {
	return &GetPostsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// 香评详情 ##25.04.01## 历史遗留文件，暂不处理
func (l *GetPostsLogic) GetPosts(req *types.PostDetailReq) (*types.PostDetailResp, error) {
	if req.Id == 0 {
		return nil, resultx.NewErrCode(resultx.FORUM_POST_ID_REQUIRED)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	preload := "forumPost:Id,AuthorId,ParentId"
	eagerLoad := "forumPost:forumMedia,forumPostMeta"
	preload += ",AuthorName,AuthorAvatar,AuthorLevel,Status"
	preload += ",CommentStatus,PhotoCount,CreatedAt;forumMedia:Id,Uid,Url,Thumbnail,Order"
	preload += ";forumPostMeta:likeCount,collectCount"
	platformId := globalkey.ThirdPartyPlatformWechatMini
	res, err := l.svcCtx.ForumRpc.GetPostsById(l.ctx, &forumclient.PostsDetailReq{
		Id:         pointy.GetPointer(req.Id),
		Preload:    pointy.GetPointer(preload),
		EagerLoad:  pointy.GetPointer(eagerLoad),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(platformId),
		WithMedia:  req.WithMedia,
		WithMeta:   req.WithMeta,
	})
	if err != nil {
		return nil, err
	}

	if res == nil || res.Id == nil || res.ParentId == nil || *res.Id == 0 || *res.ParentId == 0 {
		return nil, resultx.NewErrCode(resultx.FORUM_POST_STATUS_INVALID)
	}

	var photos []*types.MediaInfo
	if len(res.Media) > 0 {
		for _, v := range res.Media {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			var thumbnail *bool
			if v.Thumbnail != nil {
				thumbnail = pointy.GetPointer(*v.Thumbnail > 0)
			}
			photos = append(photos, &types.MediaInfo{
				Uid:       v.Uid,
				Id:        v.Id,
				Url:       pointy.GetPointer(url),
				Thumbnail: thumbnail,
				AltText:   v.AltText,
				Details:   v.MetaData,
				Order:     v.Order,
			})
		}
	}
	var meta []*types.MetaInfo
	var likeCount int
	var collectCount int
	if len(res.Meta) > 0 {
		for _, v := range res.Meta {
			if v.Key == nil || v.Value == nil || len(strings.TrimSpace(*v.Key)) == 0 || len(strings.TrimSpace(*v.Value)) == 0 {
				continue
			}
			key := strings.TrimSpace(*v.Key)
			val := strings.TrimSpace(*v.Value)
			if key == "_like_count" {
				likeCount, _ = strconv.Atoi(val)
			}
			if key == "_collect_count" {
				collectCount, _ = strconv.Atoi(val)
			}
			meta = append(meta, &types.MetaInfo{
				Id:    v.Id,
				Key:   pointy.GetPointer(key),
				Value: pointy.GetPointer(val),
			})
		}
	}

	return &types.PostDetailResp{
		Message: "查询成功",
		Data: &types.PostsInfo{
			PostId:         res.Id,
			ForumId:        res.ForumId,
			TopicId:        res.TopicId,
			ParentId:       res.ParentId,
			AuthorId:       res.AuthorId,
			AuthorNickname: res.AuthorNickname,
			AuthorAvatar:   res.AuthorAvatar,
			AuthorIp:       res.AuthorIP,
			PostTitle:      res.PostTitle,
			PostContent:    res.PostContent,
			PostStatus:     res.Status,
			CommentStatus:  res.CommentStatus,
			PhotoCount:     res.PhotoCount,
			Photos:         photos,
			Meta:           meta,
			LikeCount:      pointy.GetPointer(uint64(likeCount)),
			CollectCount:   pointy.GetPointer(uint64(collectCount)),
			CreatedAt:      res.CreatedAt,
			UpdatedAt:      res.UpdatedAt,
			DeletedAt:      res.DeletedAt,
		},
	}, nil
}
